package gov.kqqzyyy.monkey.orderpad.mytools;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.widget.Toast;

import com.socks.library.KLog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Objects;

public class ImageSaveUtil {

    private static final String SD_PATH = Environment.getExternalStorageDirectory().getPath() + "/order_screenshot/";

    public static boolean saveBitmap2file(Bitmap bmp, Context context, String name) {
        boolean result = false;
//        String SD_PATH = Objects.requireNonNull(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)).getAbsolutePath() + File.separator;
        String savePath = null;
        String fileName = name + ".jpg";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            savePath = SD_PATH;
        } else {
            Toast.makeText(context, "保存失败！", Toast.LENGTH_SHORT).show();
            result = false;
        }
        File filePic = new File(savePath + fileName);
        try {
            if (!filePic.exists()) {
                boolean mkdirResult = Objects.requireNonNull(filePic.getParentFile()).mkdirs();
                KLog.d("APE", "mkdirs:" + mkdirResult);
                boolean creResult = filePic.createNewFile();
                KLog.d("APE", "createNewFile:" + creResult);
            }
            FileOutputStream fos = new FileOutputStream(filePic);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            KLog.d("APE", "image save success");
            result = true;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + savePath + fileName)));
        return result;
    }
}
